﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using EPiServer.DynamicContent;
using EPiServer.Core.Html;

namespace EPiBoost.Core.Helpers
{
	public static class HtmlStringHelper
	{
		public static string StripHtml(string htmlText, int maxTextLength = 0, string moreTextMarker = "...")
        {
            if (string.IsNullOrEmpty(htmlText))
            {
                return string.Empty;
            }

            //If the text contains DynamicContents, replace those with an empty string
            var regexPattern = new StringBuilder(@"<span[\s\W\w]*?classid=""");
            regexPattern.Append(DynamicContentFactory.Instance.DynamicContentId.ToString());
            regexPattern.Append(@"""[\s\W\w]*?</span>");

            htmlText = Regex.Replace(htmlText, regexPattern.ToString(), string.Empty, RegexOptions.IgnoreCase | RegexOptions.Multiline);
 

            string result =  TextIndexer.StripHtml(htmlText, maxTextLength == 0 ? htmlText.Length : maxTextLength);
			if (result.EndsWith("..."))
			{
				result = result.Substring(0, result.Length - 3);
				result = string.Format("{0}{1}", result, moreTextMarker);
			}
			return result;
        }
	}
}
